<template>
  <view class="login-container">
    <view class="logo-area">
      <image class="logo" src="@/static/logo.png" mode="aspectFit"></image>
      <text class="app-name">星蓝商务留学签证系统</text>
    </view>

    <view class="login-form">
      <button
        class="open-btn"
        open-type="chooseAvatar"
        @chooseavatar="handleChooseAvatar"
      >
        <u-avatar :src="form.avatar" size="80"></u-avatar>
      </button>
      <u-input
        type="nickname"
        v-model="form.nickname"
        placeholder="请输入用户名"
      />
      <u-button type="primary" @click="handlePasswordLogin" shape="circle"
        >登录</u-button
      >
    </view>

    <view class="agreement">
      <text>登录即表示同意</text>
      <text class="link">《用户协议》</text>
      <text>和</text>
      <text class="link">《隐私政策》</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { type MPWechatLoginParams, mpWechatLogin } from "@/common/apis/user";
import { useUserStore } from "@/store/modules/user";
import { ref } from "vue";

const userStore = useUserStore();

const form = ref<MPWechatLoginParams>({
  avatar: "",
  code: "",
  nickname: "",
});

const handlePasswordLogin = () => {
  if (!form.value.avatar) {
    uni.showToast({ title: "请上传头像", icon: "none" });
    return;
  }
  if (!form.value.nickname) {
    uni.showToast({ title: "请输入昵称", icon: "none" });
    return;
  }
  uni.login({
    provider: "weixin",
    success: async (loginRes) => {
      form.value.code = loginRes.code;
      const response = await userStore.fetchMpWechatLogin(form.value);
      if (response) {
        uni.switchTab({ url: "/pages/index/index" });
      } else {
        uni.showToast({ title: "登录失败，请重试", icon: "none" });
      }
    },
    fail: (err) => {
      uni.showToast({ title: "登录失败，请重试", icon: "none" });
      console.error("微信登录失败:", err);
    },
  });
};

function handleChooseAvatar(e: any) {
  if (e.detail.avatarUrl) {
    form.value.avatar = e.detail.avatarUrl;
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  padding: 40rpx;
  background-color: #f8f8f8;

  .logo-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 200rpx;
    margin-bottom: 100rpx;

    .logo {
      width: 150rpx;
      height: 150rpx;
      border-radius: 30rpx;
    }

    .app-name {
      margin-top: 30rpx;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .login-form {
    display: flex;
    flex-direction: column;
    gap: 30rpx;
  }
}

.agreement {
  position: fixed;
  bottom: 60rpx;
  left: 0;
  right: 0;
  text-align: center;
  font-size: 24rpx;
  color: #999;

  .link {
    color: #2979ff;
  }
}

.open-btn {
  padding: 0;
  border: none;
}
</style>
